//
//  PurchaseNowViewController.m
//  ChunLaiZhuangClient
//
//  Created by xielihui on 16/3/20.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "PurchaseNowViewController.h"
#import "SettlementViewController.h"
#import "ProdcutDetaiModel.h"
#import "PurchaseNowTableViewCell1.h"
#import "PurchaseNowTableViewCellTwo.h"
#import "SKTagView.h"
#import "SKTag.h"

@interface PurchaseNowViewController ()<SettleupCommodityDelegate, UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *backView;
@property (nonatomic, strong) SettlementViewController *settlementVC;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) ProdcutDetaiModel *productModel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewHeightCons;
@property (nonatomic, strong) NSMutableDictionary *optionDictionary;
@property (nonatomic, assign) NSInteger quantity;
@property (weak, nonatomic) IBOutlet UIButton *purchaseBtn;
@property (nonatomic, strong) NSMutableDictionary *paramsDict;
@property (nonatomic, assign) BOOL optionalProductToCart;
@end

@implementation PurchaseNowViewController

- (id)initWithProductModel:(ProdcutDetaiModel *)model isOptionalProductToCart:(BOOL)optional{
    if (self = [super init]) {
        self.productModel = model;
        self.quantity = model.data.minimum.intValue;
        self.optionDictionary = [NSMutableDictionary dictionary];
        self.optionalProductToCart = optional;
    }
    return self;
}

- (id)initWithProductModel:(ProdcutDetaiModel *)model {
    if (self = [super init]) {
        self.productModel = model;
        self.quantity = model.data.minimum.intValue;
        self.optionDictionary = [NSMutableDictionary dictionary];
        self.optionalProductToCart = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView reloadData];
    self.tableView.scrollEnabled = NO;
    [self.backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closePageAction:)]];
    if (self.productModel.data.options.count > 0) {
        self.tableViewHeightCons.constant = 93.f + self.productModel.data.options.count * 64.f;
    }
    if (self.optionalProductToCart) {
        [self.purchaseBtn setTitle:@"确定" forState:UIControlStateNormal];
    }
    [self addChildViewController:self.settlementVC];
    [self.view addSubview:self.settlementVC.view];
    self.purchaseBtn.layer.cornerRadius = 24.f;
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (SettlementViewController *)settlementVC {
    if (!_settlementVC) {
        _settlementVC = [[SettlementViewController alloc] init];
        _settlementVC.view.backgroundColor = [UIColor clearColor];
        _settlementVC.view.frame = self.view.frame;
        _settlementVC.delegate = self;
        _settlementVC.view.left = self.view.width;
    }
    return _settlementVC;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.productModel.data.options.count > 0) {
        return self.productModel.data.options.count + 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.row == 0) {
        NSString *identifier = @"purchaseCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"PurchaseNowTableViewCell1" owner:nil options:nil] lastObject];
        }
        ((PurchaseNowTableViewCell1 *)cell).spaceLine.hidden = !(self.productModel.data.options.count > 0);
        [((PurchaseNowTableViewCell1 *)cell) updateWithProductInfo:self.productModel];
        ((PurchaseNowTableViewCell1 *)cell).closePageBlock = ^(){
            [self closePageAction:nil];
        };
        ((PurchaseNowTableViewCell1 *)cell).addProductNumBlock = ^(NSInteger quantity){
            self.quantity = quantity;
            [self getPrice];
        };
        ((PurchaseNowTableViewCell1 *)cell).minusProductNumBlcok = ^(NSInteger quantity){
            self.quantity = quantity;
            [self getPrice];
        };
    } else {
        NSString *identifier = @"purchaseOptionCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"PurchaseNowTableViewCellTwo" owner:nil options:nil] lastObject];
        }

        ProductOptionModel *model = [self.productModel.data.options objectAtIndex:indexPath.row - 1];

        [((PurchaseNowTableViewCellTwo *)cell) updateWithOptionValues:model.product_option_value];
        ((PurchaseNowTableViewCellTwo *)cell).selectOptionBlock = ^(ProductOptionValueModel *selectValueModel) {
            if (selectValueModel) {
                [self.optionDictionary setObject:selectValueModel.product_option_value_id forKey:[NSString stringWithFormat:@"%@", model.product_option_id]];
            } else {
                [self.optionDictionary removeObjectForKey:[NSString stringWithFormat:@"%@", model.product_option_id]];
            }
        };
        if (indexPath.row != self.productModel.data.options.count) {
            ((PurchaseNowTableViewCellTwo *)cell).spaceLine.hidden = YES;
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        self.tableViewHeightCons.constant = 93.f;
        return 93.f;
    } else {
        PurchaseNowTableViewCellTwo *optionCell = (PurchaseNowTableViewCellTwo *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        CGFloat height = [optionCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize].height;
        if (indexPath.row != self.productModel.data.options.count) {
            height -= 20;
        }
        self.tableViewHeightCons.constant += height;
        return height;
    }
}

- (void)closePageAction:(id)sender {
    if ([self.delegate respondsToSelector:@selector(closePurchaseViewController:)]) {
        [self.delegate closePurchaseViewController:self];
    }
}

- (void)getPrice {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.productModel.data.product_id forKey:@"product_id"];
    [params setObject:@(self.quantity) forKey:@"quantity"];
    if (self.optionDictionary.count > 0) {
        [params setObject:self.optionDictionary forKey:@"option"];
    }
    [ApiClient getProductPrice:params didFinishLoaded:^(ProductPriceModel *model, NSString *path) {
        if ([model.status isEqual:@(1)]) {
            PurchaseNowTableViewCell1 *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            NSString *price = model.data.special.length > 0 ? model.data.special : model.data.price;
            [cell updatePriceLabel:price];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
    
}
- (IBAction)purchaseNowAction:(id)sender {
    if (self.optionalProductToCart) {
        //带选项商品选择选项后加入购物车
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:self.productModel.data.product_id forKey:@"product_id"];
        [params setObject:@(self.quantity) forKey:@"quantity"];
        if (self.optionDictionary.count > 0) {
            [params setObject:self.optionDictionary forKey:@"option"];
        }
        [[LKDHud shareHud] showLoadingView];
        [ApiClient addProductToShopBag:self.productModel.data.product_id quantity:self.quantity options:self.optionDictionary didFinishLoaded:^(KXJson *json, NSString *path) {
            [[LKDHud shareHud] hideLoadingView];
            BOOL success = NO;
            if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
                success = YES;
            }
            if ([self.delegate respondsToSelector:@selector(addOptionalProductToShopBag:success:)]) {
                [self.delegate addOptionalProductToShopBag:self success:success];
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            [[LKDHud shareHud] hideLoadingView];
            if ([self.delegate respondsToSelector:@selector(addOptionalProductToShopBag:success:)]) {
                [self.delegate addOptionalProductToShopBag:self success:NO];
            }
        }];
    } else {
        //立即购买
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:self.productModel.data.product_id forKey:@"product_id"];
        [params setObject:@(self.quantity) forKey:@"quantity"];
        if (self.optionDictionary.count > 0) {
            [params setObject:self.optionDictionary forKey:@"option"];
        }
        [[LKDHud shareHud] showLoadingView];
        [ApiClient purchaseProduct:params didFinishLoaded:^(CheckoutModel *model, NSString *path) {
            [[LKDHud shareHud] hideLoadingView];
            if ([model.status isEqual:@(1)]) {
                self.settlementVC.purchaseParams = params;
                [self.settlementVC getCheckoutInfos];
                [UIView animateWithDuration:.3f animations:^{
                    self.settlementVC.view.left = 0.f;
                }];
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            [[LKDHud shareHud] hideLoadingView];
        }];
    }
}

#pragma --mark settlementVC delegates 

- (void)closeSettlementViewController:(SettlementViewController *)settleVC {
    [UIView animateWithDuration:.3f animations:^{
        self.settlementVC.view.left = self.view.width;
    }];
}

- (void)payEndAction:(SettlementViewController *)settleVC {
    [UIView animateWithDuration:.3f animations:^{
        self.settlementVC.view.left = self.view.width;
        [self closePageAction:nil];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
